﻿package tk.mystudio.permission.service;

import java.util.List;
import java.util.Observable;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mystudio.permission.bean.Resource;
import tk.mystudio.permission.bean.RoleResource;
import tk.mystudio.permission.dao.ResourceDao;
import tk.mystudio.permission.dao.RoleResourceDao;
import tk.mystudio.util.Order;
import tk.mystudio.util.Page;

@Service
@Transactional
public class ResourceService extends Observable {

	private Logger logger = Logger.getLogger(ResourceService.class);
	
	@javax.annotation.Resource
	private ResourceDao resourceDao;
	@javax.annotation.Resource
	private RoleResourceDao roleResourceDao;

	@Transactional
	public Resource save(Resource res) {
		resourceDao.save(res);
		return res;
	}

	@Transactional
	public void deleteById(int id) {
		resourceDao.removeByPhysics(id);
		//TODO 测试
		RoleResource roleResource = new RoleResource();
		roleResource.setResourceId(id);
		roleResourceDao.removeByPhysics(roleResource);
		updateSecuriyResourceData(); // 刷新授权资源信息
	}

	@Transactional
	public Resource update(Resource res) {
		resourceDao.update(res);
		updateSecuriyResourceData(); // 刷新授权资源信息
		return res;
	}

	@Transactional(readOnly = true)
	public Resource getResourceById(int id) {
		return resourceDao.get(id);
	}

	@Transactional
	public List<Resource> getAllResources() {
		return resourceDao.getList(null);
	}

	// 刷新授权资源信息
	private void updateSecuriyResourceData() {
		logger.info("====== 刷新资源数据 ======");
		setChanged();
		notifyObservers();
	}
	
	@Transactional(readOnly = true)
	public Page<Resource> listByPage(Resource example, Page<Resource> page, Order[] orders) {
		try {
			return resourceDao.listByPage(example, page, orders);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Transactional
	public Integer countResource(Resource resource) {
		return resourceDao.getCount(resource);
	}

//	@Transactional
//	public List<Resource> findResource(Resource resource, Integer page,
//			Integer pageSize, String sortField, String order) {
//		return list;
//	}
	
	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}
	
	public void setRoleResourceDao(RoleResourceDao roleResourceDao) {
		this.roleResourceDao = roleResourceDao;
	}

}
